import Club from '../../../database/models/club'
import {PlayerModel} from '../../../database/models/player'
import ClubMemeber from '../../../database/models/clubMember'
import RoomRecord from '../../../database/models/roomRecord'
import Members = Chai.Members

export const typeDefs = `
  type Club {
    _id: String!,
    name:String!,
    shortId: String!,
    owner: PlayerInfo!
    gameType: String!
    createAt: String! 
  }
  
  type RoomScore{
	  score : Int,
    name : String,
	  headImgUrl : String,
	  shortId : String
  }
  
  type Room{
      _id: String!
      roomNum: String!,
      category: String,
      createAt: String!
      players: [PlayerInfo]!
      scores: [RoomScore]!
  }
  
  type MemberShip{
    _id: String!
    member: PlayerInfo!
    joinAt: String!
    gameType:String!
  }
`

export const queryDefs = `
  clubs : [Club]!
  clubRooms (clubId: String!) :[Room]!
  clubInfo(clubId: String!): Club
  clubMembers (clubId:String!) : [MemberShip]!
`

export const mutationDefs = `
  createClub(
    gameType:String!
    playerShortId: String!
    shortId: String!
    name: String!
  ):Club
  
  removeMemberShip(memberShipId:String!):Boolean
  
  dismissClub(clubId:String!): Boolean
`

export const resolvers = {
  Query: {
    async clubs(_) {
      const records = await Club.find()
        .sort({createAt: -1})
        .populate('owner')
        .lean()
      return records
    },

    async clubRooms(_, {clubId}) {
      const club = await Club.findById(clubId)
      if (club) {
        return RoomRecord
          .find({club: clubId})
          .sort({createAt: -1})
          .lean()
          .exec()
      } else {
        throw Error('NO_SUCH_CLUB')
      }
    },
    async clubMembers(_, {clubId}) {
      const members = await ClubMemeber.find({club: clubId}).sort({joinAt: -1}).populate('member')
      return members
    },

    async clubInfo(_, {clubId}) {
      return Club.findById(clubId).populate('owner')
    }
  },

  Mutation: {
    async createClub(_, {name, gameType, shortId, playerShortId}) {
      const players = await PlayerModel.find({shortId: playerShortId}).exec()
      if (players.length !== 1) {
        throw Error('错误的玩家 ID')
      }
      const owner = players[0]

      const oldCLub = await Club.findOne({owner: owner._id, gameType})
      if (oldCLub) {
        throw Error('你已经创建了一个亲友圈')
      }

      const joinedClub = await ClubMemeber.count({member: owner._id, gameType})
      if (joinedClub >= 5) {
        throw Error('你已经加入了5个亲友圈,不能再创建亲友圈了')
      }

      const club = new Club({name, shortId, owner: owner._id, gameType})
      await club.save()
      await ClubMemeber.create({club: club._id, member: owner._id, joinAt: new Date(), gameType})

      club.owner = owner
      return club
    },

    async removeMemberShip(_, {memberShipId}) {
      const membership = await ClubMemeber.findById(memberShipId).populate('club').lean()

      if (membership.club.owner === membership.member) {
        throw Error('不能删除亲友圈主')
      }


      await ClubMemeber.remove({_id: memberShipId})
      return true
    },

    async dismissClub(_, {clubId}) {
      const club = await Club.findById(clubId)
      if (!club) {
        throw Error('该亲友圈不存在')
      }

      await ClubMemeber.remove({club: club._id})
      await club.remove()
      return true
    }

  }
}
